/*
 * =====================================================================================
 *
 *       Filename:  TMCSpinLock.h
 *
 *    Description:  TMCSpinLock.h
 *
 *         Author:  Younghyun Jo (2013-20887)
 *   Organization:  Department of Computer Science and Engineering
 *                  Seoul National University
 *
 * =====================================================================================
 */

#ifndef PARTICIPANT
  #define PARTICIPANT Participant
#endif

#include <tmc/spin.h>
#include <tmc/sync.h>
#include <arch/atomic.h>
#include <arch/inline.h>
#include <sys/time.h>

#define spin_lock_init(lock) tmc_spin_mutex_init(lock)
#define spin_lock_destruct(lock) {;} // nothing
#define spin_lock_acquire tmc_spin_mutex_lock
#define spin_lock_release tmc_spin_mutex_unlock
#define spin_lock_t tmc_spin_mutex_t

class Participant;

class TMCSpinLock {
  public:
    TMCSpinLock(const int numParticipants)
    {
      spin_lock_init(&lock);
    }

    ~TMCSpinLock()
    {
      spin_lock_destruct(&lock);
    }

    inline void finalize_initialization() {}

    spin_lock_t lock;
    int sharedVar;
};

class Participant {
  public:
    Participant(TMCSpinLock* const tmcLock)
      : _tmcLock(tmcLock) {}

    inline bool synchronize() const {
      spin_lock_acquire(&(_tmcLock->lock));
      _tmcLock->sharedVar += 1;
      spin_lock_release(&(_tmcLock->lock));
    }

  private:
    TMCSpinLock* const _tmcLock;
};

